package com.zwq.controller;


import cn.hutool.jwt.JWT;
import cn.hutool.jwt.signers.JWTSignerUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wssky.entity.UmsWechatMemberRelation;
import com.wssky.wxlogin.WXScanReturn;
import com.zwq.domain.Login;
import com.zwq.service.LoginService;
import com.zwq.service.UmsMemberFeignService;
import com.zwq.util.R;
import com.zwq.util.XMLUtils;
import com.zwq.wxlogin.WXLoginRequest;
import com.zwq.wxlogin.WXLoginResponse;
import com.zwq.wxlogin.WXLoginTickets;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;


@RestController
@RequestMapping("/log")
@CrossOrigin
public class LoginController {
    @Resource
    LoginService loginService;
    @Resource
    RedisTemplate redisTemplate;
    @Resource
    StringRedisTemplate stringRedisTemplate;
    @Resource
    UmsMemberFeignService umsMemberFeignService;
    @RequestMapping("/logins")
    public R logins(@RequestBody Login login){
        QueryWrapper<Login> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",login.getUsername());
        Login one = loginService.getOne(queryWrapper);
        if(one.getUsername()!=null){
            return R.ERROR(1,"用户名已存在");
        }
        boolean save = loginService.save(login);
        return R.OK(save);
    }

    @RequestMapping("/login")
    public R login(@RequestBody Login login){
        QueryWrapper<Login> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",login.getUsername());
        Login one = loginService.getOne(queryWrapper);
        if(one.getUsername()==null){
            return R.ERROR(1,"用户名已存在");
        }
        if(!(one.getPassword().equals(login.getPassword()))){
            return R.ERROR(1,"密码错误");
        }
        redisTemplate.opsForValue().setIfAbsent("one",one,60, TimeUnit.MINUTES);
        String token = JWT.create()
                .setPayload("user", one)
                .setSigner(JWTSignerUtil.none())
                .sign();
        return R.OK(token);
    }
    @PostMapping("/token")
    public R token(String wxKey) throws Exception {
        String appID="wx68613797c5f7e5b7";
        String appsecret="7ed500710b37d3cb79fbfecf7e51b00a";

        String result = WXLoginRequest.requestGetOne(appID, appsecret);
        WXLoginResponse wxLoginResponse = JSON.parseObject(result, WXLoginResponse.class);
        String tokens = wxLoginResponse.getAccess_token();//令牌
        Long expires_in = wxLoginResponse.getExpires_in();//过期时间
        System.out.println("result:"+result);
        if(expires_in<=0){
            return R.ERROR(1,"令牌信息已过期，请重新认证");
        }
        String sceneString = "{\"expire_seconds\": 604800, \"action_name\": \"QR_SCENE\", \"action_info\": {\"scene\": {\"scene_id\": " + wxKey + "}}}";
        String tickets = WXLoginRequest.getTickets(tokens, sceneString);
        WXLoginTickets wxLoginTickets = JSON.parseObject(tickets, WXLoginTickets.class);
        String wxCodeUrl="https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=";
        String ticket = wxLoginTickets.getTicket();
        System.out.println("url:"+wxCodeUrl+ticket);
        return R.OK(wxCodeUrl+ticket);
    }
    @PostMapping("/check/wp")
    public R checkWp() throws Exception {
        String body = " <xml>\n" +
                "     *      *      <ToUserName><![CDATA[gh_0dbd96c7a630]]></ToUserName>\n" +
                "     *      *      <FromUserName><![CDATA[o-_pI50AcwRZtw_6p6nxE4GSKC8U]]></FromUserName>\n" +
                "     *      *      <CreateTime>1727104353</CreateTime>\n" +
                "     *      *      <MsgType><![CDATA[event]]></MsgType>\n" +
                "     *      *      <Event><![CDATA[SCAN]]></Event>\n" +
                "     *      *      <EventKey><![CDATA[123]]></EventKey>\n" +
                "     *      *      <Ticket><![CDATA[gQGw8DwAAAAAAAAAAS5odHRwOi8vd2VpeGluLnFxLmNvbS9xLzAyVjRVb1lTWFdkOEQxVVBUV2hDMUoAAgSzfPFmAwSAOgkA]]></Ticket>\n" +
                "     *      * </xml>";
        WXScanReturn wxScanReturn = XMLUtils.parseXml2Obj(body, WXScanReturn.class);

        UmsWechatMemberRelation uwmr=loginService.findRelationByOid(wxScanReturn.getFromUserName());

        if (uwmr==null){
            return R.ERROR(-1,"微信扫码登录失败,请先进行注册");
        }

        String wxResult = JSON.toJSONString(uwmr);

        stringRedisTemplate.opsForValue().set("scanAffirm","ture",5,TimeUnit.MINUTES);
        stringRedisTemplate.opsForValue().set("wxxResult",wxResult,2,TimeUnit.HOURS);

        return R.OK();
    }
    @GetMapping("findWechatResult")
    public R findWechatResult(String wxKey){
        System.out.println("wxKey:"+wxKey);
        String scanAffirm = stringRedisTemplate.opsForValue().get("scanAffirm");
        if (scanAffirm==null||scanAffirm.equals("")) {
            return R.ERROR(1,"二维码已失效,请先进行扫码");
        }
        System.out.println("scanAffirm:"+scanAffirm);
        if (!scanAffirm.equals("true")){
            return R.ERROR(1,"微信扫描登录失败,请先进行注册");
        }
        return R.OK();
    }
}
